from typing import List
from ninja import Router, File, Form
from accounts.schemas import CustomUserIn,ErrorSchema,SuccessSchema,ProductListingIn,BuyProductsIn
from ninja.pagination import paginate
from core.bcos import BcosApi
import json
router = Router()

#创建普通EOA用户
@router.post('/createUser',response={200: SuccessSchema, 500: ErrorSchema},auth = None)
def create_user(request, payload: Form[CustomUserIn]): #因为使用Form，所以传参时需要使用x-www-form-urlencoded格式，但如果不适用Form，则需要使用application/json格式
  bcos_api = BcosApi()
  try:
      chainUserInfo = bcos_api.createUser(payload.userId)
      print(chainUserInfo,type(chainUserInfo))
      return 200,SuccessSchema(
          status='200',
          message='用户创建成功.',
          data={
             "blockaddress": str(chainUserInfo.get("address")),
             "privatekey": str(chainUserInfo.get("privatekey")),
             "publickey": str(chainUserInfo.get("publickey")),
          }
      )
  except Exception as e:
    print(f"Error: {e}")
    return 500,ErrorSchema(status='500',message='用户创建失败.')



#创建商户EOA用户
@router.post('/createMerchant',response={200: SuccessSchema, 500: ErrorSchema},auth = None)
def create_merchant(request, payload: Form[CustomUserIn]):
  bcos_api = BcosApi()
  try:
      chainUserInfo = bcos_api.createUser(payload.userId)
      # print(chainUserInfo)
      return 200,SuccessSchema(
          status='200',
          message='商户创建成功.',
          data={
             "blockaddress": str(chainUserInfo.get("address")),
             "privatekey": str(chainUserInfo.get("privatekey")),
             "publickey": str(chainUserInfo.get("publickey")),
          }
      )
  except Exception as e:
    print(f"Error: {e}")
    return 500,ErrorSchema(status='500',message='商户创建失败.')
  


# 上架商品 - 删除了productType、description、categoryName参数
@router.post('/listProduct', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def list_product(request, payload: ProductListingIn):
    bcos_api = BcosApi()
    try:
       
        result = bcos_api.listProduct(payload.privatekey, payload.productId, payload.productName, 
                                    int(payload.price), payload.imageUrl, payload.parentTradeHash)
        print(f"上架结果: {result}")
        return 200, SuccessSchema(
            status='200',
            message='商品上架成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='商品上架失败.')

# 购买单个商品
@router.post('/buyProduct', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def buy_product(request, privatekey: str, listingHash: str, buyer: str):
    bcos_api = BcosApi()
    try:
        result = bcos_api.buyProduct(privatekey, listingHash, buyer)
        print(f"购买结果: {result}")
        return 200, SuccessSchema(
            status='200',
            message='商品购买成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='商品购买失败.')

# 批量购买商品
@router.post('/buyMultipleProducts', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def buy_multiple_products(request, payload: BuyProductsIn):
    """
    批量购买商品
    Args:
        privatekey: 买家私钥
        listingHashes: 上架哈希列表字符串数组，格式: ["hash1", "hash2", "hash3"]
        buyer: 买家地址
    """
    bcos_api = BcosApi()
    try:
        # 验证参数
        if not payload.listingHashes or not isinstance(payload.listingHashes, list):
            return 500, ErrorSchema(status='500', message='上架哈希列表不能为空或格式错误')
        
        result = bcos_api.buyMultipleProducts(payload.privatekey, payload.listingHashes, payload.buyer)
        print(f"批量购买结果: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='批量购买成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='批量购买失败.')

# 获取记录详情
@router.get('/getRecord', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def get_record(request, recordHash: str):
    bcos_api = BcosApi()
    try:
        result = bcos_api.getRecord(recordHash)
        print(f"记录详情: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='获取记录详情成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='获取记录详情失败.')

# 获取用户记录
@router.get('/getUserRecords', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def get_user_records(request, user: str):
    bcos_api = BcosApi()
    try:
        result = bcos_api.getUserRecords(user)
        print(f"用户记录: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='获取用户记录成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='获取用户记录失败.')

# 获取上架记录对应的交易记录
@router.get('/getListingTrades', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def get_listing_trades(request, listingHash: str):
    bcos_api = BcosApi()
    try:
        result = bcos_api.getListingTrades(listingHash)
        print(f"上架交易记录: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='获取上架交易记录成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='获取上架交易记录失败.')

# 获取用户可转售的商品
@router.get('/getUserResellableProducts', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def get_user_resellable_products(request, user: str):
    bcos_api = BcosApi()
    try:
        result = bcos_api.getUserResellableProducts(user)
        print(f"用户可转售商品: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='获取用户可转售商品成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='获取用户可转售商品失败.')

# 验证记录哈希
@router.get('/verifyRecordHash', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def verify_record_hash(request, recordHash: str):
    bcos_api = BcosApi()
    try:
        result = bcos_api.verifyRecordHash(recordHash)
        print(f"记录哈希验证: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='记录哈希验证成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='记录哈希验证失败.')

# 获取完整溯源链
@router.get('/getFullTraceChain', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def get_full_trace_chain(request, startHash: str):
    bcos_api = BcosApi()
    try:
        result = bcos_api.getFullTraceChain(startHash)
        print(f"完整溯源链: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='获取完整溯源链成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='获取完整溯源链失败.')

# 获取结构化完整溯源链
@router.get('/getStructuredTraceChain', response={200: SuccessSchema, 500: ErrorSchema}, auth=None)
def get_structured_trace_chain(request, startHash: str):
    """
    获取结构化的完整溯源链
    
    Args:
        startHash: 起始哈希（可以是listing hash或trade hash）
    
    Returns:
        结构化的溯源链数据，每个步骤包含详细的角色信息和描述
    """
    bcos_api = BcosApi()
    try:
        result = bcos_api.getStructuredTraceChain(startHash)
        print(f"结构化溯源链: {result}")
        
        return 200, SuccessSchema(
            status='200',
            message='获取结构化溯源链成功.',
            data=result
        )
    except Exception as e:
        print(f"Error: {e}")
        return 500, ErrorSchema(status='500', message='获取结构化溯源链失败.')

